package com.cloudwebsoft.framework.util;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.LinkedList;
import java.util.List;

import static java.lang.System.out;


public class HttpHelper {

    // get 请求
    public static String httpGet(String url, String[][] headers, List<NameValuePair> list) {
        try {
            URIBuilder uri = new URIBuilder(url);
            // get请求带参数
            if (list != null) {
                uri.setParameters(list);
            }

            HttpUriRequest uriRequest = new HttpGet(uri.build());
            if (null != headers) {
                for (String[] header: headers) {
                    uriRequest.addHeader(header[0], header[1]);
                }
            }

            try (CloseableHttpClient httpClient = declareHttpClientSSL(url)) {
                CloseableHttpResponse httpresponse = httpClient.execute(uriRequest);
                HttpEntity httpEntity = httpresponse.getEntity();
                return EntityUtils.toString(httpEntity, REQ_ENCODEING_UTF8);
            } catch (ClientProtocolException e) {
                out.println(String.format("http请求失败，uri{%s},exception{%s}", url, e));
            } catch (IOException e) {
                out.println(String.format("IO Exception，uri{%s},exception{%s}", url, e));
            }
        } catch (URISyntaxException e) {
            LogUtil.getLog(HttpHelper.class).error(e);
        }
        return null;
    }

    /**
     * 不带参数数get，但也可以在url中传参
     * @param url
     * @param headers
     * @return
     */
    public static String httpGet(String url, String[][] headers) {
        HttpUriRequest uriRequest = new HttpGet(url);
        if (null != headers) {
            for (String[] header: headers) {
                uriRequest.addHeader(header[0], header[1]);
            }
        }

        try (CloseableHttpClient httpClient = declareHttpClientSSL(url)) {
            CloseableHttpResponse httpresponse = httpClient.execute(uriRequest);
            HttpEntity httpEntity = httpresponse.getEntity();
            return EntityUtils.toString(httpEntity, REQ_ENCODEING_UTF8);
        } catch (ClientProtocolException e) {
            out.println(String.format("http请求失败，uri{%s},exception{%s}", url, e));
        } catch (IOException e) {
            out.println(String.format("IO Exception，uri{%s},exception{%s}", url, e));
        }
        return null;
    }

    // post 请求
    public static String httpPost(String url, String[][] headers, String params) {
        HttpPost post = new HttpPost(url);
        post.addHeader("Content-Type", "application/json;charset=" + REQ_ENCODEING_UTF8);
        if (null != headers) {
            for (String[] header: headers) {
                post.addHeader(header[0], header[1]);
            }
        }

        // 设置传输编码格式
        StringEntity stringEntity = new StringEntity(params, REQ_ENCODEING_UTF8);
        stringEntity.setContentEncoding(REQ_ENCODEING_UTF8);
        post.setEntity(stringEntity);
        HttpResponse httpresponse;
        try (CloseableHttpClient httpClient = declareHttpClientSSL(url)) {
            httpresponse = httpClient.execute(post);
            HttpEntity httpEntity = httpresponse.getEntity();
            return EntityUtils.toString(httpEntity, REQ_ENCODEING_UTF8);
        } catch (ClientProtocolException e) {
            return String.format("http请求失败，uri{%s},exception{%s}", url, e);
        } catch (IOException e) {
            return String.format("IO Exception，uri{%s},exception{%s}", url, e);
        }
    }

    private static CloseableHttpClient declareHttpClientSSL(String url) {
        if (url.startsWith("https://")) {
            return sslClient();
        } else {
            return HttpClientBuilder.create().setConnectionManager(httpClientConnectionManager).build();
        }
    }

    /**
     * 设置SSL请求处理
     *
     */
    private static CloseableHttpClient sslClient() {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] xcs, String str) {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] xcs, String str) {
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLConnectionSocketFactory sslConnectionSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
            return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new RuntimeException(e);
        }
    }

    // this is config
    private static final String REQ_ENCODEING_UTF8 = "utf-8";
    private static PoolingHttpClientConnectionManager httpClientConnectionManager;

    public HttpHelper() {
        httpClientConnectionManager = new PoolingHttpClientConnectionManager();
        httpClientConnectionManager.setMaxTotal(100);
        httpClientConnectionManager.setDefaultMaxPerRoute(20);
    }
}
